import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';

import '../../route/route_utils.dart';
import '../../sample/configure/constants.dart';
import '../../theme.dart';
import '../../utils/persistent_storage.dart';
import 'login_page.dart';

/// 忘记密码页面
class ResetpassPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ResetpassPageState();
  }
}

class _ResetpassPageState extends State<ResetpassPage> {
  final TextEditingController _account = TextEditingController(text: "");
  final TextEditingController _code = TextEditingController(text: "");

  final TextEditingController _password = TextEditingController(text: "");
  final TextEditingController _savepaddword = TextEditingController(text: "");

  // 用户隐私协议
  bool _isAgreementChecked = false;

  bool _isCounting = false;
  int _seconds = 60;

  @override
  void initState() {
    super.initState();

    _loadAgreementStatus();
  }

  // 用户隐私协议
  void _loadAgreementStatus() async {
    final protocolAndPrivacy = await SharedPreferencesUtil.instance
        .getBool(SampleConstants.storageKeyAgreementPrivacyStatus);
    setState(() {
      _isAgreementChecked = protocolAndPrivacy == true;
    });
  }

  //重置密码
  void _savepassword() async {
    // 正则表达式验证11位手机号
    RegExp phoneRegex = RegExp(r'^1[3-9]\d{9}$');

    if (_account.text.isEmpty) {
      showToast("请输入手机号");
      return;
    } else if (!phoneRegex.hasMatch(_account.text)) {
      showToast("请输入有效的11位手机号");
      return;
    }

    if (_code.text.isEmpty) {
      showToast("请输入验证码");
      return;
    }

    final RegExp usernameRegex =
    // RegExp(r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]{7,}$');
    RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$');

    if (!usernameRegex.hasMatch(_password.text)) {
      showToast("密码必须大于6位，且包含数字和字母");
      return;
    }

    if (!usernameRegex.hasMatch(_savepaddword.text)) {
      showToast("密码必须大于6位，且包含数字和字母");
      return;
    }

    if (_password.text != _savepaddword.text) {
      showToast("两次密码必须一样");
      return;
    }

    // 验证验证码是否正确
    bool swticher = await Api.instance.usergetsave(phone: _account.text,code: _code.text);
    if (!swticher) {
      showToast("验证码不正确");
      return;
    }

    // 重置密码成功
    bool passswticher = await Api.instance.usercodepassword(username: _account.text,password: _savepaddword.text);
    if (passswticher) {
      showToast("密码重置成功");
      RouteUtils.pushAndRemoveUntil(context, LoginPage());
    }
  }

  void _getcode () async {
    String data = await Api.instance.usergetcode(phone: _account.text);
    LogUtils.w(data);
    if (data.isEmpty) {
      showToast("验证码发送成功");
    }
  }

  void _startCountdown() async {
    if (_isCounting) return;

    // 正则表达式验证11位手机号
    RegExp phoneRegex = RegExp(r'^1[3-9]\d{9}$');

    if (_account.text.isEmpty) {
      showToast("请输入手机号");
      return;
    } else if (!phoneRegex.hasMatch(_account.text)) {
      showToast("请输入有效的11位手机号");
      return;
    }

    setState(() {
      _isCounting = true;
    });

    // 获取验证码
    print("发送验证码${_account.text}");
    _getcode ();

    // 测试
    // setState(() {
    //   _code.text = data;
    // });

    Future.doWhile(() async {
      await Future.delayed(Duration(seconds: 1));
      setState(() {
        if (_seconds > 0) {
          _seconds--;
        } else {
          _isCounting = false;
          _seconds = 60;
        }
      });
      return _isCounting;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(left: 30, right: 30),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 40),
              Container(
                alignment: Alignment.centerLeft, // 设置容器内容左对齐
                child: Text(
                  "重置密码",
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    fontFamily: "PingFang SC, PingFang SC",
                  ),
                ),
              ),
              Spacer(),
              // 手机号输入框

              TextField(
                controller: _account,
                decoration: InputDecoration(
                  hintText: "请输入手机号",
                  hintStyle: TextStyle(
                    color: Color(0xFFCCCCCC),
                  ),
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFff6966), // 默认边框颜色
                    ),
                  ),

                  // 修改边框颜色
                  // enabledBorder: UnderlineInputBorder(
                  //   borderSide: BorderSide(
                  //     color: Color(0xFFff6966), // 默认边框颜色
                  //   ),
                  // ),

                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888), // 获得焦点时的边框颜色
                    ),
                  ),
                ),
                cursorColor: Color(0xFF00c888), // 设置光标颜色
              ),
              Spacer(),
              // 验证码输入框

              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _code,
                      decoration: InputDecoration(
                        hintText: "请输入验证码",
                        hintStyle: TextStyle(
                          color: Color(0xFFCCCCCC),
                        ),
                        border: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xFFCCCCCC),
                          ),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xFF00c888),
                          ),
                        ),
                      ),
                      cursorColor: Color(0xFF00c888),
                    ),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: _isCounting ? null : _startCountdown,
                    child: Text(
                      _isCounting ? "$_seconds 秒后重试" : "获取验证码",
                      style: TextStyle(color: Color(0xFF00C888)),
                    ),
                  ),
                ],
              ),
              Spacer(),
              TextField(
                controller: _password,
                decoration: InputDecoration(
                  hintText: "请输入密码",
                  hintStyle: TextStyle(
                    color: Color(0xFFCCCCCC),
                  ),
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                ),
                cursorColor: Color(0xFF00c888),
              ),
              SizedBox(height: 8),

              Transform.translate(
                offset: Offset(-32.sp, 0), // 向左偏移 15
                child: Text(
                  "密码必须包含数字和字母，且长度超过8位",
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFcccccc),
                  ),
                ),
              ),
              Spacer(),

              TextField(
                controller: _savepaddword,
                decoration: InputDecoration(
                  hintText: "请再次输入密码",
                  hintStyle: TextStyle(
                    color: Color(0xFFCCCCCC),
                  ),
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                ),
                cursorColor: Color(0xFF00c888),
              ),
              const SizedBox(height: 10),
              _buildAgreementCheckbox(),
              const SizedBox(height: 40),
              _buildLoginButton(),
              // 注册
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),

            ],
          ),
        ),
      ),
    );
  }

  // 用户隐私协议
  Widget _buildAgreementCheckbox() {
    return Center(
      child: Row(
        children: [
          Transform.translate(
            offset: const Offset(-15, 0), // 向左移动24像素，可以根据实际情况调整
            child: Theme(
              data: ThemeData(
                unselectedWidgetColor: SampleThemeConfigure.colorTextHint,
              ),
              child: Checkbox(
                value: _isAgreementChecked,
                onChanged: (bool? newValue) {
                  setState(() {
                    _isAgreementChecked = newValue ?? false;
                  });
                  SharedPreferencesUtil.instance.setBool(
                      SampleConstants.storageKeyAgreementPrivacyStatus,
                      newValue ?? false);
                },
                checkColor: Colors.white,
                activeColor: SampleThemeConfigure.colorPrimary,
              ),
            ),
          ),
          Transform.translate(
            offset: const Offset(-20, 0), // 文字向左偏移15像素
            child: const Text(
              "我已阅读并同意",
              style: TextStyle(
                  color: SampleThemeConfigure.colorTextSub, fontSize: 12),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: InkWell(
              onTap: () {
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (context) => UserProtocolPage()),
                // );
              },
              child: const Text(
                '《用户协议》',
                style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
              ),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: const Text(
              "与",
              style: TextStyle(
                  color: SampleThemeConfigure.colorTextSub, fontSize: 12),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: InkWell(
              onTap: () {
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (context) => PrivacyPage()),
                // );
              },
              child: const Text(
                '《隐私政策》',
                style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 验证码按钮
  Widget _buildLoginButton() {
    return SizedBox(
      width: 400, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: _savepassword,
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '重置密码',
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }
}
